//
//  Toast.swift
//  sss
//
//  Created by hrrMac on 2020/6/30.
//  Copyright © 2020 hrrMac. All rights reserved.
//

import Foundation

class Toast{
    let mb: MBProgressHUD = MBProgressHUD(view: UIApplication.shared.keyWindow!)
    weak var superView: UIView?
    static let sharedInstance: Toast = {
        let instance = Toast()
        return instance
    }()
}

/**
 弹在window上的loading 慎用
 */

///在window上弹出提示框
public func mbShowToastToWindow(_ text: String, delay: Float = 1.2){
    UIApplication.shared.keyWindow!.mbShowToast(text, delay: delay)
}

///在window上loading
public func mbShowLoadingTextToWindow(_ text: String?){
    UIApplication.shared.keyWindow!.mbShowLoadingText(text)
}

///弹框消失
public func mbDismiss(){
    Toast.sharedInstance.mb.hide(animated: true)
    Toast.sharedInstance.mb.alpha = 0.0
}

extension UIView{
    ///将提示框加载在视图上
    @discardableResult
    func mbShowToast(_ text: String, delay: Float = 1.2) -> UIView{
        if Toast.sharedInstance.superView != self {
            Toast.sharedInstance.mb.removeFromSuperview()
            self.addSubview(Toast.sharedInstance.mb)
            Toast.sharedInstance.superView = self;
        }
        Toast.sharedInstance.mb.alpha = 1.0
        Toast.sharedInstance.mb.detailsLabel.text = text
        Toast.sharedInstance.mb.detailsLabel.font = UIFont.systemFont(ofSize: 15)
        Toast.sharedInstance.mb.mode = .text
        Toast.sharedInstance.mb.show(animated: true)
        Toast.sharedInstance.mb.hide(animated: true, afterDelay: TimeInterval(delay))
        return self
    }
    
    ///loading
    @discardableResult
    func mbShowLoadingText(_ text: String?) -> UIView{
        if Toast.sharedInstance.superView != self {
            Toast.sharedInstance.mb.removeFromSuperview()
            self.addSubview(Toast.sharedInstance.mb)
            Toast.sharedInstance.superView = self;
        }
        Toast.sharedInstance.mb.alpha = 1.0
        Toast.sharedInstance.mb.detailsLabel.text = text ?? ""
        Toast.sharedInstance.mb.detailsLabel.font = UIFont.systemFont(ofSize: 15)
        Toast.sharedInstance.mb.mode = .indeterminate
        Toast.sharedInstance.mb.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2)
        Toast.sharedInstance.mb.show(animated: true)
        return self
    }
    
    ///将mb移动到所有视图最前方
    func mbBringToFront(){
        if (Toast.sharedInstance.superView != nil) {
            Toast.sharedInstance.superView!.bringSubviewToFront(Toast.sharedInstance.mb)
        }
    }
    
}


///后续功能：现在讲Loading写成了一个单例，有可能存在多个界面含有loading的情况

